//////////////////////////////////////////////////////////////////////////////////
//                                                                              //
//  This file is part of the buola project (https://code.google.com/p/buola/).  //
//                                                                              //
//  Copyright(c) 2007-2012 Xavi Gratal                                          //
//  gratal AT gmail DOT com                                                     //
//                                                                              //
//  Buola is free software: you can redistribute it and/or modify               //
//  it under the terms of the GNU General Public License as published by        //
//  the Free Software Foundation, either version 3 of the License, or           //
//  (at your option) any later version.                                         //
//                                                                              //
//  Buola is distributed in the hope that it will be useful,                    //
//  but WITHOUT ANY WARRANTY; without even the implied warranty of              //
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the               //
//  GNU General Public License for more details.                                //
//                                                                              //
//  You should have received a copy of the GNU General Public License           //
//  along with buola.  If not, see <http://www.gnu.org/licenses/>.              //
//                                                                              //
//////////////////////////////////////////////////////////////////////////////////

//TODO:Parse some general command-line options

#include <buola/buola.h>
#include <buola/app/cplugin.h>
#include <buola/io/curi.h>
#include <buola/xml.h>
#include <dlfcn.h>
#include <buola/app/cinitfunction.h>
#include <buola/io/cresourcefinder.h>

namespace buola {

void CPlugin::Load(const std::string &pName)
{
#if BUOLA_PLATFORM_MAC
    std::string lName=pName+".dylib";
#else
    std::string lName=pName+".so";
#endif
    void *lHandle=dlopen(lName.c_str(),RTLD_LAZY);

    if(!lHandle)
    {
        std::string lString(I18N("Can't dlopen plugin ")+lName+": "+dlerror());
        throw XNotFound(lString);
    }
}

//Load all plugins of a certain type

void CPlugin::LoadAll(const std::string &pName)
{
    CInitFunction::Reset();

    xml::CDoc lDoc;
    lDoc.Load(io::registry_finder().FindFile("plugins.xml"));

    xml::CNode lRoot=lDoc.Root().FirstChild(pName);

    for(auto lChild : lRoot.Children())
    {
        if(lChild.MatchesName("plugin"))
        {
            std::string lFile;
            lChild.GetAttrib("file",lFile);
            Load(lFile);
        }
    }

    CInitFunction::RunAll();
}

/*namespace buola*/ }
